/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * inicioSesion.java
 *
 * Created on 16/11/2010, 11:20:45 PM
 */
package co.srm.vistas;

import co.srm.entidades.Usuario;
import co.srm.manejadores.ManejadorUsuario;
import co.srm.vistas.VentanaPrincipal;
import com.nilo.plaf.nimrod.NimRODLookAndFeel;
import com.nilo.plaf.nimrod.NimRODTheme;
import com.sun.swing.internal.plaf.basic.resources.basic;
import javax.swing.UnsupportedLookAndFeelException;
import net.java.swingfx.waitwithstyle.InfiniteProgressPanel;
import java.io.IOException;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
//import javax.mail.MessagingException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/*
 * @author JORGE
 */
public class inicioSesion extends javax.swing.JFrame {

    public static Usuario userActual;
    public static Timestamp fechaInicioSesion;
    //public static ConfiguracionInicial config=new ConfiguracionInicial("configuracion.properties");
//    public static ConfiguracionInicial config = new ConfiguracionInicial("configuracion.properties");

    /** Creates new form inicioSesion */
    public inicioSesion() throws SQLException, UnsupportedLookAndFeelException {
        super(":: SRM 1.0:: Inicio de Sesion");

        setLocationRelativeTo(null);

//        try {
//            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
//            SwingUtilities.updateComponentTreeUI(this);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
         try {
            NimRODTheme nt = new NimRODTheme(getFrames().getClass().getResource("/co/" + "srm/Utilidades/basic2.theme"));
            NimRODLookAndFeel nf = new NimRODLookAndFeel();
            NimRODLookAndFeel.setCurrentTheme(nt);
            UIManager.setLookAndFeel(nf);

            SwingUtilities.updateComponentTreeUI(this);
            this.pack();
            //UIManager.setLookAndFeel(new com.nilo.plaf.nimrod.NimRODLookAndFeel());
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
//        try {
//            configuracionInicial();
//        } catch (IOException ex) {
//            Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        botonInicioSesion = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SRM - 1.0");
        setResizable(false);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(null);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setLabelFor(txtLogin);
        jLabel1.setText("Usuario:");

        txtLogin.setFont(new java.awt.Font("Lucida Bright", 2, 14));

        jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel2.setText("Contraseña:");

        txtPassword.setFont(new java.awt.Font("Lucida Bright", 2, 14));
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtPassword)
                    .addComponent(txtLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18))
        );

        jPanel2.add(jPanel1);
        jPanel1.setBounds(0, 60, 330, 80);

        botonInicioSesion.setFont(new java.awt.Font("Lucida Bright", 1, 12));
        botonInicioSesion.setText("Iniciar");
        botonInicioSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonInicioSesionActionPerformed(evt);
            }
        });
        jPanel2.add(botonInicioSesion);
        botonInicioSesion.setBounds(130, 150, 92, 23);

        botonCancelar.setFont(new java.awt.Font("Lucida Bright", 1, 12));
        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });
        jPanel2.add(botonCancelar);
        botonCancelar.setBounds(230, 150, 90, 23);

        jLabel3.setFont(new java.awt.Font("Monotype Corsiva", 3, 36)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/co/srm/vistas/iconos/SRM_banner_400x61.png"))); // NOI18N
        jPanel2.add(jLabel3);
        jLabel3.setBounds(0, 0, 400, 60);

        jLabel4.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/co/srm/vistas/iconos/SRM_logo_66x66.png"))); // NOI18N
        jLabel4.setLabelFor(txtLogin);
        jPanel2.add(jLabel4);
        jLabel4.setBounds(320, 70, 70, 70);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonInicioSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonInicioSesionActionPerformed
        // TODO add your handling code here:
        inicioDeSesion();

    }//GEN-LAST:event_botonInicioSesionActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // TODO add your handling code here:
        //metodo deprecado para cerrar la venta
        //        this.hide();
        int resp = JOptionPane.showConfirmDialog(this, "Realmente deseas salir ", ":: SRM ::", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_OPTION) {
            // JOptionPane.showMessageDialog(this,"Gracias por usar ZonaSoft");
            this.dispose();
        }
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        // TODO add your handling code here:
        if ((evt.getKeyCode() == KeyEvent.VK_ENTER)) {
            inicioDeSesion();
        }


    }//GEN-LAST:event_txtPasswordKeyPressed
//
//    public void configuracionInicial() throws IOException {
//        config.cargarArchivo();
////        config.cargarArchivo2();
//        String skin = config.buscarPropiedad("ventana.skin");
//        SubstanceLookAndFeel.setSkin(skin);
//
//    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//         try{
//      //  UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");
//              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        }catch (Exception e){
//       e.printStackTrace();
//       }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                    try {
                        new inicioSesion().setVisible(true);
                    } catch (SQLException ex) {
                        Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnsupportedLookAndFeelException ex) {
                        Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
                    }
            }
        });
    }

    /* public static void main(String args[]) {
    
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    //new inicioSesion().setVisible(true);
    
    }
    });
    }*/
    int numeroInicio = 0;

    private void inicioDeSesion() {

        if (this.txtLogin.getText().equals("") || this.txtPassword.getPassword().toString().equals("")) {
            JOptionPane.showMessageDialog(null, "Campo vacío, verifique sus datos por favor", "error", JOptionPane.ERROR_MESSAGE);
        } else {
            String cadenaclave = "";
            String login = this.txtLogin.getText();
            char[] c = this.txtPassword.getPassword();
            for (int x = 0; x < c.length; x++) {
                char ch = c[x];
                String a = String.valueOf(ch);
                cadenaclave = cadenaclave + a;
            }

            // UsuarioJdbc userjdbc = new UsuarioJdbc();
            ManejadorUsuario user = new ManejadorUsuario();

            //Usuario u=userjdbc.iniciarSesionUsuario(login, cadenaclave);
            Usuario u = user.login(login, cadenaclave);
            if (u == null) {
                JOptionPane.showMessageDialog(null, "Usuario No Existe, verifique sus datos", "error", JOptionPane.ERROR_MESSAGE);
            } else {

                userActual = u;
//            if (u.getLogin_usuario() == null || u.getLogin_usuario().endsWith("_")) {
//            } else {
                final InfiniteProgressPanel glasspane = new InfiniteProgressPanel();
                this.setGlassPane(glasspane);
                glasspane.start();
                glasspane.setText("Iniciando sesion - ZonaSoft 1.0");
                this.setVisible(true);
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                        }
//                                JOptionPane.showMessageDialog(null, "Sesion Iniciada");
                        setVisible(false);
                        /* aqui termina la ejecucion de la ventana de inicio de sesion
                        despues de validar como tal el inicio de sesion, incremento en 1 el numero de inicio de sesion*/
                        numeroInicio++;
                        /* si el numero de eventos para iniciar sesion es igual a 1 muestrame la ventana principal
                        esto para evitar que se ejecuten mas de una ventana principal */
                        boolean bandera = false;
                        if (numeroInicio == 1) {
                            VentanaPrincipal.mostrar();

////                           try {
////                                mailMac.enviarAuditoriaSession();
////                                bandera=true;
////
////                            } catch (MessagingException ex) {
////                                System.out.println("ex = " + ex);
////                                bandera=false;
////                                Logger.getLogger(inicioSesion.class.getName()).log(Level.SEVERE, null, ex);
////                            }
////                           if (bandera == false){
////                           JOptionPane.showMessageDialog(null, "Verifique su conexion a internet","Error en Auditoria Online ",JOptionPane.PLAIN_MESSAGE);
////                            System.exit(0);
////                           }
//////                           VentanaPrincipal.mostrar();
                        } // comprobacion de numero de logueos

                    } // run
                });
                thread.start();
            }
            Date ahora = new Date();
            fechaInicioSesion = new Timestamp(ahora.getTime());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonInicioSesion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables
}
// asi estaba antes para acceder, en el primer  paquete la clase principal

/*

/* To change this template, choose Tools | Templates
 * and open the template in the editor.


package zonasoft;

import zonasoft.Vistas.VentanaPrincipal;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.watermark.SubstanceImageWatermark;

/**
 *
 * @author JORGE

public class Principal {

/**
 * @param args the command line arguments

public static void main(String[] args) {
// TODO code application logic here
VentanaPrincipal vp = new  VentanaPrincipal();


SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.BusinessBlackSteelSkin");

vp.setLocation(200, 200);
//vp.setSize(1500, 800);
vp.setLocationRelativeTo(null);
vp.setVisible(true);




}

}


 */
